<?php


namespace app\msgapi\service;


use app\msgapi\model\{AdminUser, AuthGroup, User};
use think\facade\Cache;

class HsadminService extends BaseService
{
    protected $limit; //每页默认数量
    public function __construct(AdminUser $adminUser)
    {
        parent::__construct();
        $this->model = $adminUser;
        $this->limit = config('page.defaule_limit');

    }

    public function getLists()
    {
        $limit = input('limit')?:$this->limit;   $keywords = input('?keywords')? input('keywords/s') : null;
        $keywords && $where[] = ['name|username|email','like',"%$keywords%"];
        $list = $this->model->with(['groupname','qw_name'])->withoutField('password')->where('id', '>', 1)->where($where)->order('add_time')->paginate($limit)->toArray();
        return success_json('成功',$list);
    }

    public function getRows($id)
    {
        $info = $this->model->withoutField('password')->findOrEmpty($id)->toArray();
        $info['deparment_user'] = [];
        $info['user_deparment'] = [];
        if($info['user_lst']){ //前端要求加的逻辑
            $tmp_arr = [];
            foreach (explode(',',$info['user_lst']) as $k => $v)
            {
                $tmp_info = User::where('userid','=',$v)->column('department_list','userid');
                if(!$tmp_info) continue;
                $tmp_arr[$k]['userid'] = $v;
                $tmp_arr[$k]['deparment_lst'] = $tmp_info[$v];
            }
            $info['deparment_user'] = $tmp_arr;
        }
        if($info['userid']){
            $info['user_deparment'] = User::where('userid','=',$info['userid'])->value('department_list');
        }
//        $rows = $this->arrayVal($this->model->withoutField('password')->findOrEmpty($id));// 排除密码字段
        return success_json('成功',$info);
    }

    public function _save()
    {
        $data = input('post.');
        // 验证器根据场景验证数据
        if($check = $this->model->validate($data,($data['id']?'edit':'add'))){
            return error_json($check);
        }
        if($data['deparment_lst'] || $data['user_lst']){
            $data['deparment_lst'] =  trim(str_replace('，',',',$data['deparment_lst']),', '); //去掉左右两边的空字符和英文逗号
            $data['user_lst'] =  trim(str_replace('，',',',$data['user_lst']),', ');
        }

        try{
            if($data['id']){    // 更新
                if($data['userid'] && (AdminUser::where('userid',$data['userid'])->count() > 0) &&(AdminUser::where('userid',$data['userid'])->value('id') != $data['id'])) return error_json('保存失败,重复绑定成员');
                $filed = ['username','userid','is_show','name','group_id','last_pass','password','deparment_lst','user_lst','email'];
                if($data['password']) {
                    $data['last_pass'] = time();// 编辑时如果修改密码时更新当前时间
                    Cache::delete("admin_{$data['username']}"); //重置密码时删除密码错误缓存
                } else {
                    unset($filed[5]);// 不修改密码时不写入
                }
                $this->model::update($data,['id'=>$data['id']],$filed);
            }else{      // 新增
                if($data['userid'] && (AdminUser::where('userid',$data['userid'])->count() > 0)) return error_json('保存失败,重复绑定成员');
                $data['add_time'] = date('Y-m-d H:i:s');
                $data['last_pass'] = time();// 新增时写入当前时间，防止开启改密周期

                $this->model::create($data);
            }
            return success_json('保存成功');
        }catch (\Exception $e){
            return error_json('保存失败，请重试');
        }
    }

    public function _delete($id, bool $force = false)
    {
        if ($id == 1) {
            return ajax_return(1,'默认管理员不可删除');
        }
        return parent::_delete($id, $force);
    }

    // 全部用户组的键值对
    public function getAllGroup()
    {
        return AuthGroup::column('title','id');
    }

    //获取管理员的通讯录管理范围
    public static function getAdminRange($admin_groupid,$adminid)
    {
        // 检测管理员权限
        if($admin_groupid == 1) {
            //超级管理员组拥有所有权限,包括通讯录管理范围所有权限.
            $admin_range = 'all';
        }else{
            $admin_range = AdminUser::where('id','=',$adminid)->field('deparment_lst,user_lst')->findOrEmpty()->toArray();
        }
        return $admin_range;
    }

    /**获取管理员可见账号
     * @param $admin_groupid
     * @param $adminid
     * @param $is_inside 是否内部调用
     * @return AdminUser|array|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAdminAccount($admin_groupid,$adminid,$is_inside = false)
    {
        if(($admin_groupid == 1) && ($adminid == 1)) $where = [];
        if(($admin_groupid == 1) && ($adminid != 1)) $where[] = ['id','<>',1];
        if($admin_groupid != 1) $where[] = ['id','=',$adminid];
        if(!$is_inside){
            $adminlst = AdminUser::field('id,name,username')->where($where)->select()->toArray();
            return success_json('成功',$adminlst);
        }
        $adminlst = AdminUser::where($where)->column('id');
        return $adminlst;
    }

    /**
     * 获取已绑定userid
     * @return \think\response\Json
     */
    public function getBindUserList()
    {
        $userList = $this->model->column('userid');
        return success_json('成功',$userList);
    }

    /**
     * 生成账号
     * @param array $data
     * @return \think\response\Json
     */
    public function accountGenerator(array $data)
    {
        //查询该用户是否已经有账号了
        if (!$data['userid'] || !$data['type'] || !$data['group_id'] || !$data['auth_range']) {
            return error_json('参数错误');
        }
        $userExist = $this->model::where([['userid','=',$data['userid']]])->count();
        if ($userExist) {return error_json('该成员已绑定过账号');}
        //查询成员信息及成员状态
        $userInfo  = User::where([['status','=',1],['userid','=',$data['userid']]])->findOrEmpty()->toArray();
        if (!$userInfo) {return error_json('成员信息不存在或者状态错误');}
        //通过后开始生成账号,查询是否重复,重复后重新生成账号
        $usernameExist = $this->model::where([['username','=',$data['userid']]])->count();
        if ($usernameExist) {
            do { //生成不重复的账号
                $tmpUsername = date('ymd') . mt_rand(1001, 9999);
                $usernameNo = $this->model::where([['username','=',$tmpUsername]])->count();
            }while($usernameNo > 0);
        } else {
            $tmpUsername = $data['userid'];
        }
        $createAdmin = [];
        $createAdmin['username'] = $tmpUsername; //账号
        $createAdmin['name'] = $userInfo['name']?:$tmpUsername; //名称
        $createAdmin['userid'] = $data['userid'];
        //创建密码类型
        if ($data['type'] == 1) {
            // 验证器根据场景验证数据
            $createAdmin['password'] = $data['password'];
            $createAdmin['confirm_password'] = $data['confirm_password'];
            if ($check = $this->model->validate($createAdmin, 'add')) {
                return error_json($check);
            }
        } else {
            $createAdmin['password'] = md5($tmpUsername);
            $createAdmin['confirm_password'] = md5($tmpUsername);
        }
        //授权范围
        if ($data['auth_range'] == 1) {
            $createAdmin['user_lst'] = $data['userid'];
        } else {
            if ($data['deparment_lst'] || $data['user_lst']) {
                $createAdmin['deparment_lst'] = trim(str_replace('，', ',', $data['deparment_lst'] ), ', '); //去掉左右两边的空字符和英文逗号
                $createAdmin['user_lst'] =  trim(str_replace('，', ',', $data['user_lst']), ', ');
            }
        }
        //绑定权限组
        $groupState = AuthGroup::where([['id','=',$data['group_id']]])->value('state');
        if (!$groupState || ($groupState == 0)) { return error_json('权限组不存在或已禁用'); }
        $createAdmin['group_id'] = $data['group_id'];
        $createAdmin['state'] = 1;
        $createAdmin['add_time'] = date('Y-m-d H:i:s');
        $createAdmin['last_pass'] = time();// 新增时写入当前时间，防止开启改密周期
        $this->model::create($createAdmin);
        return success_json('创建成功');
    }
}